from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
import sys
import time
from sklearn.model_selection import train_test_split
import os
import cv2 as cv
import pandas as pd
import pickle
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier

####判断目录下是否有文件X，y###
out_path = 'X'
out_path_1 = 'y'
# exists方法判断文件夹是否存在，存在返回 True
if os.path.exists(out_path):
    with open("X", 'rb') as f:
        X = pickle.load(f)
if os.path.exists(out_path_1):
    with open("y", 'rb') as f1:
        y = pickle.load(f1)
else:
    X = []
    y = []
    ##### 循环当前目录下的所有内容
    for f in os.listdir():
        if ".jpg" not in f:  # 如果不是jpg图像文件，则略过
            continue
        img = cv.imread(f, 0)  # 已灰度图读取
        ######用最近邻算法缩放到指定大小####
        img = cv.resize(img, (32,32), interpolation=cv.INTER_NEAREST)
        new_img = img.reshape(-1)
        X.append(new_img)
    print(X)
        classStr = str(f.split('')[0])
        y.append(classStr)
    print(y)
    ######直接把 x 以二进制的形式 写到文件: x_temp中#####
    with open("X", 'wb') as f:
        pickle.dump(X, f)
    with open("y", 'wb') as f1:
        pickle.dump(y, f1)
    f.close()
    f1.close()

#####train_test_split####


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)

# 3. 创建随机森林模型
start = time.time()
clf = RandomForestClassifier()
# 相当于 clf = RandomForestClassifier(n_estimators=100)
clf.fit(X_train, y_train)


# 4. 获得算法的准确率
acc = clf.score(X_test, y_test)
print("准确率：", acc)

# 5.picke clf模型
with open("clf", 'wb') as f:
    pickle.dump(clf, f)
with open("acc", 'wb') as f:
    pickle.dump(acc, f)
print("已保存保存随机森林模型clf到硬盘")


